import { ChangeDetectorRef, Component, inject, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';

import { CardInfo } from '@app/core/services/http/card-info/card-info.service';
import { CardRegex, CardRegexService } from '@app/core/services/http/card-regex/card-regex.service';
import { SharedModule } from '@app/shared/shared.module';
import { BasicConfirmModalComponent } from '@app/widget/base-modal';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NZ_MODAL_DATA, NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-validation-modal',
  standalone: true,
  imports: [SharedModule],
  templateUrl: './validation-modal.component.html',
  styleUrls: ['./validation-modal.component.less']
})
export class ValidationModalComponent extends BasicConfirmModalComponent implements OnInit {
  isSpinningAdd: boolean = false;
  isEdit!: boolean;
  validateForm!: FormGroup;
  validationResult: string = '';
  readonly nzModalData: CardRegex = inject(NZ_MODAL_DATA);
  private readonly fb: FormBuilder = inject(FormBuilder);
  private readonly cdr: ChangeDetectorRef = inject(ChangeDetectorRef);
  private readonly messageService: NzMessageService = inject(NzMessageService);
  private readonly cardRegexService: CardRegexService = inject(CardRegexService);

  constructor(override modalRef: NzModalRef) {
    super(modalRef);
  }

  protected getCurrentValue(): Observable<NzSafeAny> {
    if (!this.validateForm.valid) {
      return of(false);
    }
    return of({ ...this.validateForm.value });
  }

  initForm(): void {
    this.validateForm = this.fb.group({
      pattern: new FormControl('', {
        validators: [Validators.required]
      }),
      content: new FormControl('', {
        validators: [Validators.required]
      })
    });

    if (this.nzModalData) {
      this.validateForm.patchValue({ pattern: this.nzModalData.regexexpression });
    }
  }

  // 校验正则表达式
  validateRegex(): void {
    if (this.validateForm.invalid) {
      return; // 如果表单未填写完整，直接返回
    }

    const pattern = this.validateForm.get('pattern')?.value; // 获取正则表达式
    const content = this.validateForm.get('content')?.value; // 获取内容
    this.cardRegexService.ValidateCardRegex(pattern, content).subscribe((res: CardInfo[]) => {
      if (res?.length > 0) {
        this.validationResult = res.map(r => r.cardnumber).join(',');
        this.cdr.detectChanges();
      }
    });
  }

  ngOnInit(): void {
    this.initForm();
    this.isEdit = !!this.nzModalData;
  }
}
